package com.nc.shop.service.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.nc.shop.service.dao.CarDao;
import com.nc.shop.service.dao.ShopDao;
import com.nc.shop.service.feign.UserFeign;
import com.nc.shop.service.model.dto.CarDto;
import com.nc.shop.service.model.entity.CarEntity;
import com.nc.shop.service.model.entity.ShopEntity;
import com.nc.shop.service.service.CarService;
import com.nc.shop.service.service.RedisService;
import com.plug.BeanUtil;
import com.plug.result.ReqPage;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v1/car")
@Api
public class CarController {
    @Autowired
    RedisService redisService;
    @Autowired
    CarService carService;
    @Autowired
    CarDao carDao;
    @Autowired
    ShopDao shopDao;
    @Autowired
    UserFeign userFeign;
    @Autowired
    HttpServletRequest request;

    @ApiOperation("新增商品到购物车")
    @PostMapping("{userId}/{shopId}")
    public RetResult insertCar(@PathVariable String userId, @PathVariable String shopId, Integer number) {
        return carService.insert(userId, shopId, number);
    }

    @DeleteMapping("{id}")
    @ApiOperation("根据购物车id删除")
    public RetResult insertCar(@PathVariable String id) {
        return carService.out(id);
    }

    @PostMapping("all")
    @ApiOperation("购物车商品列表")
    public RetResult all(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        CarEntity entity = JSON.parseObject(req.toJSONString(), CarEntity.class);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("shopId", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<CarEntity> example = Example.of(entity, matcher);
        Page<CarEntity> pages = carDao.findAll(example, pageable);
        List<CarEntity> pageList = pages.getContent();
        List<CarDto> pageListDto = Lists.newArrayList();
        pageList.forEach(item -> {
            CarDto carDto = BeanUtil.convertToBean(item, CarDto.class);
            carDto.setShopEntity(shopDao.findById(item.getShopId()).get());
            net.sf.json.JSONObject user = net.sf.json.JSONObject.fromObject(userFeign.userDetail(carDto.getUserId()).getData());
            carDto.setUserName(user.getString("nickName"));
            pageListDto.add(carDto);
        });
        return RetResponse.makeRsp(0, "成功", pageListDto, (int) pages.getTotalElements());
    }

    @PostMapping("user/all")
    @ApiOperation("当前登陆人购物车商品列表")
    public RetResult userAll() {
        JSONObject user = JSONObject.parseObject(redisService.get(request.getHeader("token")));
        List<CarEntity> carEntities = carDao.findByUserId(user.getString("id"));
        List<CarDto> pageList = Lists.newArrayList();
        carEntities.forEach(item -> {
            CarDto carDto = BeanUtil.convertToBean(item, CarDto.class);
            carDto.setShopEntity(shopDao.findById(item.getShopId()).get());
            carDto.setUserName(user.getString("nickName"));
            pageList.add(carDto);
        });
        return RetResponse.makeOKRsp(pageList);
    }
}
